package com.ddwl.message.service;

import com.alibaba.fastjson.JSON;
import com.ddwl.common.constant.BaseEnum;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.message.model.WebSocketMessage;
import com.ddwl.schema.bo.message.WebSocketMessageBo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: hemiaojun
 * @Date: 2020/12/12
 * @Description: 登录认证推送
 */
@ServerEndpoint("/ws/auth/{sessionId}")
@Slf4j
@Component
public class WsAuthService {

    private static AtomicInteger onlineCount = new AtomicInteger(0);
    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static ConcurrentHashMap<String, WsAuthService> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sessionId") String sessionId) {
        this.session = session;
        if (webSocketMap.containsKey(sessionId)) {
            webSocketMap.remove(sessionId);
            webSocketMap.put(sessionId, this);
        } else {
            webSocketMap.put(sessionId, this);
            addOnlineCount();
        }
        log.info("用户连接:" + sessionId + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("sessionId") String sessionId) {
        if (webSocketMap.containsKey(sessionId)) {
            webSocketMap.remove(sessionId);
            subOnlineCount();
        }
        log.info("用户退出:" + sessionId + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:" + session.getId() + ",报文:" + message);
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + session.getId() + ",原因:" + error.getMessage());
    }

    /**
     * 实现服务器主动推送
     */
    public String sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("用户:" + session.getId() + ",推送异常：{}", e.getMessage());
            return "error";
        }
        return "success";
    }

    /**
     * 发送自定义消息
     */
    public String sendInfo(String message, @PathParam("sessionId") String sessionId) {
        log.info("发送消息到:" + sessionId + "，报文:" + message);
        if (StringUtils.hasText(sessionId) && webSocketMap.containsKey(sessionId)) {
            return webSocketMap.get(sessionId).sendMessage(message);
        } else {
            log.error("用户" + sessionId + ",不在线！");
            return "error";
        }
    }

    public String pushMessage(WebSocketMessageBo bo) {
        List<WebSocketMessage> list = new ArrayList<>();
        WebSocketMessage wsMessage = BeanConverUtils.convertBean(bo, WebSocketMessage.class);
        list.add(wsMessage);
        String result = sendInfo(JSON.toJSONString(list), bo.getSessionId());
        if ("success".equals(result)) {
            wsMessage.setStatus(BaseEnum.StatusEnum.ENABLE.getCode());
        } else {
            wsMessage.setStatus(BaseEnum.StatusEnum.DISABLE.getCode());
        }
        return result;
    }


    public static synchronized int getOnlineCount() {
        return onlineCount.get();
    }

    public static synchronized void addOnlineCount() {
        WsAuthService.onlineCount.getAndIncrement();
    }

    public static synchronized void subOnlineCount() {
        WsAuthService.onlineCount.getAndDecrement();
    }

}
